<template>
  <div>
    <div class="share-bg">
      <div>
        <Currency
          :changeData="state.changeData"
          :styleItem="state.clientStyle"
          :bibiStatus="bibiStatus"
        />
      </div>
    </div>
    <div class="quote-page">
      <div class="quote-box">
        <div class="quote-content quotebg">
          <div
            class="tab-box quotet3 mb-30 flex js-st align-center point bdb-borderBase"
          >
            <div
              class="tab text-14"
              @click="changeTab(1)"
              :class="{
                'quotet2 text-bold active-line': state.active === 1,
              }"
            >
              {{ $t("exchange.selfSelect") }}
            </div>
			
            <div
              class="tab text-14"
              v-show="bibiStatus"
              @click="changeTab(2)"
              :class="{
                'quotet2 text-bold active-line': state.active === 2,
              }"
            >
              {{ $t("exchange.currencyMarket") }} 
            </div>
            <div
              class="tab text-14"
              @click="changeTab(3)"
              v-show="leverStatus"
              :class="{
                'quotet2 text-bold active-line': state.active === 3,
              }"
            >
              {{ $t("exchange.contractMarket") }}
            </div>
            <div
              v-if="secondStatus"
              class="tab text-14"
              @click="changeTab(4)"
              :class="{
                'quotet2 text-bold active-line': state.active === 4,
              }"
            >
              {{ $t("header.second") }}
            </div>
            <div
              v-if="stockStatus"
              class="tab text-14"
              @click="changeTab(5)"
              :class="{
                'quotet2 text-bold active-line': state.active === 5,
              }"
            >
              {{ $t("stock.stockInvestment") }}
            </div>
            <div
              v-if="stockLeverStatus"
              class="tab text-14"
              @click="changeTab(6)"
              :class="{
                'quotet2 text-bold active-line': state.active === 6,
              }"
            >
              {{ $t("stock.stockLever") }}
            </div>
            <div
              v-if="stockSecondStatus"
              class="tab text-14"
              @click="changeTab(7)"
              :class="{
                'quotet2 text-bold active-line': state.active === 7,
              }"
            >
              {{ $t("stock.stockSecond") }}
            </div>
          </div>
          <!-- 自选的两个按钮 币币交易+合约交易 -->
         
          <div class="quote-table">
            <div class="flex sp-st share-color mb-20" v-if="state.active === 1">
              <div
                class="btn radius point"
                v-for="item in state.tabbox"
                :key="item.id"
                v-show="
                  item.id === 1
                    ? bibiStatus
                    : item.id === 2
                    ? leverStatus
                    : item.id === 3
                    ? secondStatus
                    : item.id === 4
                    ? stockStatus
                    : item.id === 5
                    ? stockLeverStatus
                    : item.id === 6
                    ? stockSecondStatus
                    : ''
                "
                @click="changeName(item.id)"
                :class="state.activeName === item.id ? 'acbtn' : 'nobtn'"
              >
                {{ item.name }}
              </div>
            </div>
            <el-table
              :data="state.tableData"
              class="customer-table"
              v-loading="state.loading"
              header-cell-class-name="eltablebg"
              header-row-class-name="text-center"
              style="width: 100%"
            >
              <el-table-column
                prop="currency_name"
                :label="$t('exchange.name')"
              >
                <template #default="r">
                  <div class="flex align-center">
                    <div>
                      <i
                        class="el-icon-star-off text-20 text-regular mr-8"
                        @click.stop="
                          changeadd(
                            r.row.id,
                            r.row.is_user_currency_match,
                            r.row.is_user_stock,
                            r.row.is_user_stock_lever,
                            r.row.is_user_stock_second_lever
                          )
                        "
                        v-if="
                          !r.row.is_user_currency_match &&
                            !(
                              ((state.active === 1 && state.activeName === 4) ||
                                state.active === 5) &&
                              r.row.is_user_stock
                            ) &&
                            !(
                              ((state.active === 1 && state.activeName === 5) ||
                                state.active === 6) &&
                              r.row.is_user_stock_lever
                            ) &&
                            !(
                              ((state.active === 1 && state.activeName === 6) ||
                                state.active === 7) &&
                              r.row.is_user_stock_second_lever
                            )
                        "
                      ></i>
                      <i
                        class="el-icon-star-on text-22 text-yellow mr-8"
                        @click.stop="
                          changeadd(
                            r.row.id,
                            r.row.is_user_currency_match,
                            r.row.is_user_stock,
                            r.row.is_user_stock_lever,
                            r.row.is_user_stock_second_lever
                          )
                        "
                        v-else
                      ></i>
                    </div>
                    <span
                      v-if="
                        (state.active < 5 && state.active !== 1) ||
                          (state.active === 1 && state.activeName < 4)
                      "
                      >{{ r.row.currency_name + "/" + r.row.legal_name }}</span
                    >
                    <div
                      v-if="
                        state.active > 4 ||
                          (state.active === 1 && state.activeName > 3)
                      "
                      class="flex align-center"
                    >
                      <div>{{ r.row.stock_name }}/{{ r.row.stock_code }}</div>
                      <div>
                        <div
                          class="share-color text-10 tag us"
                          v-if="r.row.stock_type === 1"
                        >
                          US
                        </div>
                        <div
                          class="share-color text-10 tag hk"
                          v-if="r.row.stock_type === 2"
                        >
                          HK
                        </div>
                      </div>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="close_price"
                :label="$t('exchange.closePrice')"
                sortable
              >
                <template #default="r">
                  {{ $currency(r.row.close_price) }}
                </template>
              </el-table-column>
              <el-table-column
                prop="increase"
                sortable
                :label="$t('exchange.24HChange')"
              >
                <template #default="r">
                  <span
                    :class="
                      r.row.increase * 100 > 0 ? 'text-green' : 'text-red'
                    "
                  >
                    {{
                      r.row.increase > 0
                        ? "+" + (r.row.increase * 100).toFixed(2) + "%"
                        : (r.row.increase * 100).toFixed(2) + "%"
                    }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="high_price"
                :label="$t('exchange.24HHighest')"
              >
                <template #default="r">
                  <span>
                    {{
                      $currency(
                        decimalDigitsInputFilter(
                          r.row.high_price,
                          r.row.price_accuracy
                        )
                      )
                    }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="low_price"
                :label="$t('exchange.24HMinimum')"
              >
                <template #default="r">
                  <span>
                    {{
                      $currency(
                        decimalDigitsInputFilter(
                          r.row.low_price,
                          r.row.price_accuracy
                        )
                      )
                    }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="total_volume"
                :label="$t('exchange.24HTransactionAmount')"
              >
                <template #default="r">
                  <span>
                    {{
                      $currency(decimalDigitsInputFilter(r.row.total_volume, 0))
                    }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="address" :label="$t('assets.operate')">
                <template #default="r">
                  <span
                    class="point personlink"
                    @click="goTrans(r.row)"
                    type="text"
                    >{{ $t("exchange.trans") }}</span
                  >
                </template>
              </el-table-column>
              <template #empty>
                <div>
                  <Norecord :type="state.active === 1" />
                  <div class="quotet3 text-12 mb-60 l-10">
                    {{ $t("exchange.noOptional") }}
                  </div>
                  <div
                    class="empty-btn acbtn share-color radius text-16 point text-ellipsis"
                    @click="addOptional"
                  >
                    {{ $t("exchange.addOptional") }}
                  </div>
                </div>
              </template>
            </el-table>
          </div>
        </div>
      </div>
      <!-- websocket -->
      <!-- <Websocket :timeout="3000" name="涨幅" socket_type="RANKING" @change="onMessage" /> -->
    </div>
  </div>
</template>

<script>
import Currency from "@/components/homeModel/currency.vue";
import Norecord from "@/components/noRecord/NoRecord.vue";
import {
  userCurrencyMatchList,
  currencyMatchList,
  addUserCurrencyMatch,
  deleteUserCurrencyMatch,
} from "@/api/currency";
import { stockPageSimple } from "@/api/stock";
import { stockUserCurrencyMatchListSimple } from "@/api/stock";
// import Websocket from '@/components/websocket/WebSocket'
import {
  reactive,
  getCurrentInstance,
  onMounted,
  onBeforeUnmount,
  computed,
} from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { decimalDigitsInputFilter, LoginInterception } from "@/utils/common";
import { useI18n } from "vue-i18n";

export default {
  components: { Currency, Norecord },
  setup() {
    const {t} = useI18n()

    const {
      appContext: {
        app: {
          config: { globalProperties },
        },
      },
    } = getCurrentInstance();
    const { $websocketTool, $currency } = globalProperties;
    const $store = useStore();
    const $router = useRouter();
    const state = reactive({
      active: 1,
      activeName: 1,
      tabbox: [],
      list_param: { currency_match_type: 1 },
      tableData: [],
      changeData: {},
      loading: false,
      timer: null,
      clientStyle: "",
    });
    console.log('state',state);
    const changeTab = (i) => {

      state.active = i;
      if (i !== 1 && i < 5) {
        state.list_param.currency_match_type = i - 1;
        state.currentPage = 1;
        getAllList();
      } else if (i === 1) {
        changeName(1);
      } else {
        state.list_param.currency_match_type = i - 1;
        state.currentPage = 1;
        getAllStockList();
      }
    };
    const bibiStatus = computed(() => {
      let list = $store.state.user.systemInfo;
      let flag = false;
      list.forEach((ele) => {
        if (ele.key === "currency_transaction_status") {
          flag = ele.value;
        }
      });
      return flag;
    });
    const leverStatus = computed(() => {
      let list = $store.state.user.systemInfo;
      let flag = false;
      list.forEach((ele) => {
        if (ele.key === "lever_status") {
          flag = ele.value;
        }
      });
      return flag;
    });
    const secondStatus = computed(() => {
      let list = $store.state.user.systemInfo;
      let flag = false;
      list.forEach((ele) => {
        if (ele.key === "second_lever_status") {
          flag = ele.value;
        }
      });
      return flag;
    });
    const stockStatus = computed(() => {
      let list = $store.state.user.systemInfo;
      let flag = false;
      list.forEach((ele) => {
        if (ele.key === "stock_status") {
          flag = ele.value;
        }
      });
      return flag;
    });
    const stockLeverStatus = computed(() => {
      let list = $store.state.user.systemInfo;
      let flag = false;
      list.forEach((ele) => {
        if (ele.key === "stock_lever_status") {
          flag = ele.value;
        }
      });
      return flag;
    });
    const stockSecondStatus = computed(() => {
      let list = $store.state.user.systemInfo;
      let flag = false;
      list.forEach((ele) => {
        if (ele.key === "stock_second_lever_status") {
          flag = ele.value;
        }
      });
      return flag;
    });
    const changeName = (id) => {
      state.activeName = id;
      state.list_param.currency_match_type = id;
      state.currentPage = 1;
      getList();
    };
    // 获取页面宽度
    const getClientWidth = () => {
      let clientWidth = document.body.clientWidth;
      if (clientWidth < 1120) {
        state.clientStyle = "width: 100%; margin: 0 auto;";
      } else {
        state.clientStyle = "width: 1120px; margin: 0 auto;";
      }
    };
    // 更换自选
    const changeadd = (
      id,
      ischeck,
      is_user_stock,
      is_user_stock_lever,
      is_user_stock_second_lever
    ) => {
      let ischecked = false;
      if (
        (state.active < 5 && state.active !== 1) ||
        (state.active === 1 && state.activeName < 4)
      ) {
        ischecked = ischeck;
      } else if (
        (state.active === 1 && state.activeName === 4) ||
        state.active === 5
      ) {
        ischecked = is_user_stock;
      } else if (
        (state.active === 1 && state.activeName === 5) ||
        state.active === 6
      ) {
        ischecked = is_user_stock_lever;
      } else if (
        (state.active === 1 && state.activeName === 6) ||
        state.active === 7
      ) {
        ischecked = is_user_stock_second_lever;
      }
      const requestfun = ischecked
        ? deleteUserCurrencyMatch
        : addUserCurrencyMatch;
      let currency_match_type = 1;
      if (state.active === 1) {
        currency_match_type = state.activeName;
      } else {
        currency_match_type = state.active - 1;
      }
      state.loading = true;
      LoginInterception("/quote")
        .then(() => {
          requestfun({
            currency_match_id: id,
            currency_match_type: currency_match_type,
          })
            .then((res) => {
              state.loading = false;
              if (res.code === 200) {
                if (state.active === 1) {
                  getList();
                } else {
                  if (state.active < 5) {
                    getAllList();
                  } else {
                    getAllStockList();
                  }
                }
              }
            })
            .catch(() => {
              state.loading = false;
            });
        })
        .catch(() => {
          state.loading = false;
        });
    };
    // 获取全部列表
    const getAllList = () => {
      const data = { ...state.list_param };
      state.loading = true;
      currencyMatchList(data)
        .then((res) => {
          state.loading = false;
          state.tableData = res.data;
          // state.total = res.data.total
        })
        .catch((err) => {
          console.log(err);
        });
    };
    const getAllStockList = () => {
      const data = { ...state.list_param };
      data.type = data.currency_match_type - 3;
      data.currency_match_type = null;
      state.loading = true;
      stockPageSimple(data)
        .then((res) => {
          state.loading = false;
          state.tableData = res.data;
          // state.total = res.data.total
        })
        .catch((err) => {
          console.log(err);
        });
    };
    // 获取自选列表
    const getList = () => {
      if (!$store.state.user.token) {
        state.tableData = [];
        return;
      }
      let data = { ...state.list_param };
      let requestfun =
        state.activeName > 3
          ? stockUserCurrencyMatchListSimple
          : userCurrencyMatchList;
      state.loading = true;
      let param = state.activeName > 3 ? state.activeName : data;
      requestfun(param)
        .then((res) => {
          state.loading = false;
          state.tableData = res.data;
          // state.total = res.data.total
        })
        .catch((err) => {
          console.log(err);
        });
    };
    // 点击去交易
    const goTrans = (row) => {
      let id = row.id;
      let setfun = "exchange/SET_DEAL"; //默认币币
      let route = "/deal"; //默认币币
      let type = 1; //默认1币币类型 2合约类型 3秒合约
      // 先判断自选 2币币 3合约
      if (state.active === 1) {
        // 判断为1币币还是2合约
        if (state.activeName === 2) {
          setfun = "exchange/SET_LEVER";
          route = "/lever";
          type = 2;
        } else if (state.activeName === 3) {
          setfun = "exchange/SET_SECOND";
          route = "/secondlever";
          type = 3;
        } else if (state.activeName === 4) {
          setfun = "exchange/SET_STOCK";
          $store.commit("user/SET_TRADING_TAB", {
            type: "stock",
            active: row.stock_type + 1,
          });

          route = "/Stock";
        } else if (state.activeName === 5) {
          setfun = "exchange/SET_STOCK_LEVER";
          $store.commit("user/SET_TRADING_TAB", {
            type: "stockLever",
            active: row.stock_type + 1,
          });
          route = "/stockLever";
        } else if (state.activeName === 6) {
          setfun = "exchange/SET_STOCK_SECOND";
          $store.commit("user/SET_TRADING_TAB", {
            type: "stockSecond",
            active: row.stock_type + 1,
          });
          route = "/stockSecond";
        }
      } else if (state.active === 3) {
        setfun = "exchange/SET_LEVER";
        route = "/lever";
        type = 2;
      } else if (state.active === 4) {
        setfun = "exchange/SET_SECOND";        
        route = "/secondlever";
        type = 3;
      } else if (state.active === 5) {
        setfun = "exchange/SET_STOCK";
        $store.commit("user/SET_TRADING_TAB", {
            type: "stock",
            active: row.stock_type + 1,
          });
        route = "/Stock";
      } else if (state.active === 6) {
        setfun = "exchange/SET_STOCK_LEVER";
        $store.commit("user/SET_TRADING_TAB", {
            type: "stockLever",
            active: row.stock_type + 1,
          });
        route = "/stockLever";
      } else if (state.active === 7) {
        setfun = "exchange/SET_STOCK_SECOND";
        $store.commit("user/SET_TRADING_TAB", {
            type: "stockSecond",
            active: row.stock_type + 1,
          });
        route = "/stockSecond";
      }

      state.loading = true;
      if (
        (state.active < 5 && state.active !== 1) ||
        (state.active === 1 && state.activeName < 4)
      ) {
        // 获取交易对详情
        const param = {
          currency_match_type: type,
          currency_match_id: id,
        };
        $store
          .dispatch("exchange/gettradingDetail", param)
          .then((data) => {
            state.loading = false;
            $store.commit(setfun, data);
            if (state.active === 3) {
              $store.commit("user/SET_LEVER_PAGE", "level");
            } else if (state.active === 4) {
              $store.commit("user/SET_LEVER_PAGE", "second");
            }
            $router.push(route);
          })
          .catch(() => {
            state.loading = false;
          });
      } else {
        let params = {
          id: id,
        };
        $store
          .dispatch("exchange/stockDetail", params)
          .then((data) => {
            state.loading = false;
            $store.commit(setfun, data);
            console.log("data", data);
            if (state.active === 1) {
              if (state.activeName === 4) {
                $store.commit("exchange/SET_STOCK_ID", data.id);
              } else if (state.activeName === 5) {
                $store.commit("exchange/SET_STOCK_LEVER_ID", data.id);
              } else if (state.activeName === 6) {
                $store.commit("exchange/SET_STOCK_SECOND_ID", data.id);
              }
            } else if (state.active === 5) {
              $store.commit("exchange/SET_STOCK_ID", data.id);
            } else if (state.active === 6) {
              $store.commit("exchange/SET_STOCK_LEVER_ID", data.id);
            } else if (state.active === 7) {
              $store.commit("exchange/SET_STOCK_SECOND_ID", data.id);
            }
            $router.push(route);
          })
          .catch(() => {
            state.loading = false;
          });
      }
    };
    onMounted(() => {
      state.tabbox=[        
        { name: t("header.bibi"), id: 1 },
        { name: t("header.lever"), id: 2 },
        { name: t("header.second"), id: 3 },
        { name: t("stock.stockInvestment"), id: 4 },
        { name: t("stock.stockLever"), id: 5 },
        { name: t("stock.stockSecond"), id: 6 }
      ]

      getList();
      getClientWidth();
      state.timer = setInterval(() => {
        if ($websocketTool.ws && $websocketTool.ws.readyState == 1) {
          clearInterval(state.timer);
          state.timer = null;
          handleMsg({
            socket_type: "RANKING",
            subscribed: 1,
          });
          handleMsg({
            socket_type: "STOCKRANKING",
            subscribed: 1,
          });
        }
      }, 3000);
    });
    // 添加自选
    const addOptional = () => {
      if (!$store.state.user.token) {
        $router.push("/register");
        return;
      } else {
        if (state.activeName === 1) {
          changeTab(2);
        } else {
          changeTab(state.activeName + 1);
        }
      }
    };
    // 处理websocket
    const handleMsg = (msg) => {
      $websocketTool?.ws.send(JSON.stringify(msg));
      $websocketTool.ws.onmessage = function(res) {
        const message = JSON.parse(res.data);
        if (message.type === "RANKING") {
          if (
            (state.active < 5 && state.active !== 1) ||
            (state.active === 1 && state.activeName < 4)
          ) {
            onMessage(message);
          }
        }
        if (message.type === "STOCKRANKING") {
          if (
            state.active > 4 ||
            (state.active === 1 && state.activeName > 3)
          ) {
            onStockMessage(message);
          }
        }
      };
    };
    const closeMsg = (msg) => {
      if ($websocketTool.ws && $websocketTool.ws.readyState == 1) {
        $websocketTool.ws.send(JSON.stringify(msg));
      }
    };
    // websocket推送数据
    const onMessage = (val) => {
      let data = [...state.tableData];
      data.forEach((item) => {
        if (item.id === val.currencyMatchId) {
          item.close_price = val.increaseData.nowPrice;
          item.low_price = val.increaseData.lowPrice;
          item.high_price = val.increaseData.highPrice;
          item.increase = val.increaseData.increaseValue;
          item.usd_price = val.increaseData.nowPrice;
          item.transaction_amount = val.increaseData.transactionAmount;
        }
      });
      state.changeData = val;
      state.tableData = data;
    };
    const onStockMessage = (val) => {
      let data = [...state.tableData];
      data.forEach((item) => {
        if (item.id === val.stock_id) {
          item.close_price = val.increase_data.now_price;
          item.low_price = val.increase_data.low_price;
          item.high_price = val.increase_data.high_price;
          item.increase = val.increase_data.increase_value;
          item.usd_price = val.increase_data.now_price;
          item.transaction_amount = val.increase_data.transaction_amount;
        }
      });
      state.changeData = val;
      state.tableData = data;
    };
    onBeforeUnmount(() => {
      if (state.timer) {
        clearInterval(state.timer);
        state.timer = null;
      }
      closeMsg({
        socket_type: "RANKING",
        subscribed: 0,
      });
      closeMsg({
        socket_type: "STOCKRANKING",
        subscribed: 0,
      });
      closeMsg({
        socket_type: "STOCKRANKING",
        subscribed: 0,
      });
    });
    return {
      state,
      changeTab,
      changeName,
      getList,
      getAllList,
      goTrans,
      onMessage,
      decimalDigitsInputFilter,
      addOptional,
      handleMsg,
      closeMsg,
      changeadd,
      getClientWidth,
      $currency,
      bibiStatus,
      leverStatus,
      secondStatus,
      stockStatus,
      stockLeverStatus,
      stockSecondStatus,
      getAllStockList,
      onStockMessage,
    };
  },
};
</script>

<style lang="less" scoped>
.quote-page {
  padding: 20px 0 60px 0;
}
.quote-box {
  width: 1120px;
  margin: 0 auto;
}
.mb-10 {
  margin-bottom: 10px;
}
.mb-20 {
  margin-bottom: 20px;
}
.mb-30 {
  margin-bottom: 30px;
}
.mb-60 {
  margin-bottom: 60px;
}
.quote-content {
  width: 1120px;
  min-height: 620px;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}
@media (max-width: 1200px) {
  .quote-content,
  .quote-box {
    width: 100%;
  }
}
.tab-box {
  width: 100%;
  height: 48px;
  padding: 0 30px;
  box-sizing: border-box;
}
.tab {
  height: 100%;
  padding: 10px 0;
  margin-inline-end: 30px;
  position: relative;
}
.quote-table {
  padding: 0 30px;
  box-sizing: border-box;
}
.btn {
  width: 120px;
  height: 32px;
  line-height: 32px;
  margin-inline-end: 30px;
}
.empty-btn {
  width: 170px;
  height: 46px;
  line-height: 46px;
  margin: 0 auto 60px;
}
.l-10 {
  line-height: 10px;
}
.mr-8 {
  margin-inline-end: 8px;
}
.is-rtl {
  :deep(.eltablebg) {
    text-align: start;
  }
}
.text-22 {
  font-size: 22px;
  margin-inline-start: -1px;
}
.text-22 {
  font-size: 22px;
  margin-inline-start: -1px;
}
</style>
<style lang="less">
.el-table .descending .sort-caret.descending {
  border-top-color: @blue;
}
.el-table .ascending .sort-caret.ascending {
  border-bottom-color: @blue;
}
</style>
